package com.my.jli.webapi;

import com.my.jli.Service.ScoreService;
import com.my.jli.Service.StudentService;
import com.my.jli.entity.Score;
import com.my.jli.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ScoreRestController
 * @Description
 * @Author MaYu
 * @Date 2022/5/13 20:48
 * @Version 1.0
 **/
@RestController
@RequestMapping("/webapi/score")
public class ScoreRestController {

    private ScoreService scoreService;
    private StudentService studentService;
    @Autowired
    public void setScoreService(ScoreService scoreService) {
        this.scoreService = scoreService;
    }
    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping("/getAll")
    public Map<String, Score> getAll(Integer tid){
        List<Student> studentList = studentService.getByTid(tid);
        Map<String, Score> scoreMap = new HashMap<>();
        for (Student student : studentList) {
            Integer id = student.getId();
            Score score = scoreService.getBySid(id);
            String studentInfo = student.getNum() + "@" + student.getName();
            if (score != null){
                scoreMap.put(studentInfo, score);
            }
        }
        return scoreMap;
    }

    @PostMapping("/saveScore")
    public int saveScore(String num, Integer attendanceScore, Integer homeworkScore){
        if (StringUtils.hasText(num) && attendanceScore != null && homeworkScore != null){
            Student student = studentService.getByNum(num);
            Score score = scoreService.getBySid(student.getId());
            score.setAttendanceScore(attendanceScore);
            score.setHomeworkScore(homeworkScore);
            Score saveScore = scoreService.saveScore(score);
            return saveScore != null ? 1 : -1;
        } else {
            return -1;
        }
    }
}
